package com.mrjy.common.config.listener;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.mrjy.common.qtz.MemberSettlementTimeTask;
import com.mrjy.common.qtz.MemberStateTimeTask;

/**
 * 监听器监听内容
 * 添加任务在contextInitialized方法中添加
 * @author Administrator
 *
 */
public class ContextListener implements ServletContextListener {

	public static Timer timer = null;
	
	private static final long PERIOD_DAY = 24*60*60*1000;
	
	//private static final long PERIOD_MONTH =2*60*1000;
	
	/**
	 * 获取一天中的时间
	 * @param hour
	 * @param minute
	 * @param second
	 * @return
	 */
	public Date timeManage(int hour,int minute,int second){
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MINUTE, minute);
		calendar.set(Calendar.SECOND, second);
		return calendar.getTime();
	}
	
	/**
	 * 获取下月1号的时间
	 * @param hour
	 * @param minute
	 * @param second
	 * @return
	 */
	public Date timeManage2(int day,int hour,int minute,int second){
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
		calendar.set(Calendar.DAY_OF_MONTH, day);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MINUTE, minute);
		calendar.set(Calendar.SECOND, second);
		return calendar.getTime();
	}
	
	/**
	 * 获取定时器
	 * @return
	 */
	public static Timer getTimer(){
		if (timer == null) {
			timer = new Timer();
		}
		return timer;
	}
	
	/**
	 * 监听器初始化
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		if (timer == null) {
			getTimer();
		}
		
		/*会员状态检查任务*/
		/*Date date = timeManage(0, 0, 0);//设置每天0点启动-周期为一天
		timer.schedule(new MemberStateTimeTask(event.getServletContext()),date, PERIOD_DAY);*/
		/*月底会员统计并发送短信通知给分销商任务*/
		Date date2 = timeManage2(1,0, 0, 0);//设置每月1号0点启动-周期为一月
		timer.schedule(new MemberSettlementTimeTask(),date2);
		event.getServletContext().log("已经添加到任务调度表");
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		timer.cancel();
		event.getServletContext().log("定时器销毁");
	}

}
